package omg.SongHandling.DataHandling;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import omg.Error.NoConnectionError;
import omg.Error.NoValidModuleError;
import omg.Error.ParsingFailedError;
import omg.Error.SongCreationError;

public class SongManager {
	private static SongManager instance = null;

        private SongManager(){}
	public static SongManager getInstance() {
            if (null == SongManager.instance)
                SongManager.instance = new SongManager();
            return SongManager.instance;
	}

	/**
	 * 
	 * @param path
	 * @return 
	 */
	public Song getSong(String path) {
		throw new UnsupportedOperationException();
	}

	/**
         * !Notice: No support for multi link sources!
	 * Creates one or more new songs from an URI source if possible.
	 * @param uri the URI pointing to the source
         * @return the created Songs
         * @throws SongCreationError
         * @throws NoConnectionError 
	 */
	public Song[] createSong(URI uri) throws SongCreationError, NoConnectionError {
            Song song = new Song();
            try {
                Parser parser = ParserManager.getInstance().getParser(uri);
                song.setParser(parser);
                song.setLink(new URI(parser.parse()[0]));
                song.setMetadata(parser.getMetadata()[0]);

                Stream stream = StreamManager.getInstance().getStream(song);
                Converter converter = ConverterManager.getInstance().getConverter(stream);
                stream.setConverter(converter);
                song.setStream(stream);
            } catch (NoValidModuleError ex) {
                throw new SongCreationError("No fitting module could be found.", ex);
            } catch (NoConnectionError ex) {
                throw ex;
            } catch (ParsingFailedError ex) {
                Logger.getLogger("Information").log(Level.WARNING, "The selected Parsers parse() method couldn't parse the url it felt responsible for. Think about updating or removing the Parser, if this error occurs frequently.", ex);
                throw new SongCreationError("Parser failed.", ex);
            } catch (URISyntaxException ex) {
                Logger.getLogger("Information").log(Level.WARNING, "The selected Parsers parse() method didn't produce a valid audio source link.", ex);
                throw new SongCreationError("Parser failed.", ex);
            }

            Song[] songs = {song};
            return songs;
	}

	/**
	 * 
	 * @param path
	 * @return 
	 */
	private String[] parsePath(String path) {
		throw new UnsupportedOperationException();
	}

}